<?php
/**
 * Created by PhpStorm.
 * User: FDG296
 * Date: 2017/8/1
 * Time: 16:02
 * 
 * 修改历史
 * 修改时间：2018/02/06
 * 修改人：lizenan
 * 修改功能：【商城需求】便于SEO优化
 * 任务ID：463
 */
namespace backend\controllers;

use backend\models\CategoryRecommend;
use backend\models\CategoryRecommendGoods;
use backend\models\GoodsCategory;
use backend\models\GoodsCategoryBr;
use backend\models\GoodsCategoryBrGroup;
use backend\models\GoodsCategoryBrRelation;
use backend\models\GoodsCateRelation;
use backend\models\GoodsSaleEdit;
use backend\models\GoodsTag;
use backend\models\GoodsTagGroup;
use Yii;
use yii\web\AdminController;
use backend\models\UploadForm;
use backend\models\GoodsRelation;
use backend\models\GoodsListEdit;

class GoodsCategoryController extends AdminController{
    public $layout = false;
    //业务关键字
    public $service = 'GoodsCategory';
    /**
     * 商品分类首页
     */
    public function actionIndex(){
        $model = new UploadForm();
        $goods_model = new GoodsCategory();

        $list = GoodsCategory::find()->asArray()->orderBy(array('sort'=>SORT_ASC))->all();
        foreach($list as &$value){
            $value['html'] = '';
        }
        $list_tree = \common\helps\tools::getCustomerTree($list,0,0);

        //操作日志
        $this->saveLog($this->service,'商品分类查询','VIEW', '');
        return $this->render('index',['list'=>$list_tree,'model'=>$model,'goods_model'=>$goods_model]);
    }

    /**
     * 添加商品分类
     */
    public function actionAddCategory(){
        $model = new GoodsCategory();
        $data = Yii::$app->request->post();

        $data_now['img_url'] = $data['img_url'];
        $data_now['img_link'] = $data['img_link'];
        $data_now['category_name'] = trim($data['category_name']);
        $data_now['create_time'] = date('Y-m-d H:i:s',time());
        $data_now['creator'] = $model->getCreator();
        $data_now['use_flg'] = $data['use_flg'];
        $data_now['sort'] = empty($data['sort']) ? 1 : $data['sort'];
        $data_now['parent_id'] = $data['parent_id'];
        $data_now['content'] = $data['content'];
        //$data_now['nav_type'] = $data['nav_type'];
        //$data_now['big_img_url'] = $data['big_img_url'];
        //add by lizenan 20180206 【商城需求】便于SEO优化 463 start
        //$data_now['big_img_url_alt'] = $data['big_img_url_alt'];
        //$data_now['img_url_alt'] = $data['img_url_alt'];
        //add by lizenan 20180206 【商城需求】便于SEO优化 463 end
        if ($data_now['parent_id'] == 0 ){
            $data_now['level'] = 1;
        } else {
            $parent = $model::findOne(array('id'=>$data_now['parent_id']));
            $data_now['level'] = $parent['level'] + 1;
        }

        try{
            $res = Yii::$app->db->createCommand()->insert('j_materiel_category',$data_now)->execute();
            if($res > 0){
                //操作日志
                $this->saveLog($this->service,'添加商品分类','ADD', '商品分类：' .  $data_now['category_name'] . "\r\n" . \yii\helpers\Json::encode($data_now));
                $this->retJson('商品分类添加成功',200);
            }else{
                $this->retJson('商品分类添加失败',500);
            }
        }catch (\Exception $e){
            $this->retJson('添加失败，请联系管理员！',500);
        }
    }

    /**
     * 修改商品分类
     */
    public function actionUpdateCategory(){
        $model = new GoodsCategory();
        $data = Yii::$app->request->post();

        $data_now['img_url'] = $data['img_url'];
        $data_now['img_link'] = $data['img_link'];
        $data_now['category_name'] = trim($data['category_name']);
        $data_now['edit_time'] = date('Y-m-d H:i:s',time());
        $data_now['editor'] = $model->getCreator();
        $data_now['use_flg'] = $data['use_flg'];
        $data_now['sort'] = empty($data['sort']) ? 1 : $data['sort'];
        //$data_now['parent_id'] = $data['parent_id'];
        $data_now['content'] = $data['content'];
        //$data_now['nav_type'] = $data['nav_type'];
        //$data_now['big_img_url'] = $data['big_img_url_ot'];
        //add by lizenan 20180206 【商城需求】便于SEO优化 463 start
        //$data_now['big_img_url_alt'] = $data['big_img_url_alt_ot'];
        //$data_now['img_url_alt'] = $data['img_url_alt_ot'];
        //add by lizenan 20180206 【商城需求】便于SEO优化 463 end
        $res = $model::updateAll($data_now, "id=:id",array('id'=>$data['id']));
        if($res > 0){
            //操作日志
            $this->saveLog($this->service,'修改商品分类','MOD',  '商品分类：' .  $data_now['category_name'] . "\r\n"  . \yii\helpers\Json::encode($data_now));
            $this->retJson('商品分类修改成功',200);
        }else{
            $this->retJson('商品分类修改失败',500);
        }
    }

    //获取单个商品分类详情(编辑用)
    public function actionGetOneCategory(){
        $data = Yii::$app->request->post();

        $result = GoodsCategory::findOne(array('id'=>$data['id']));
        return \yii\helpers\Json::encode($result);
    }

    /**
     * 删除分类
     */
    public function actionDelCategory(){
        $model = new GoodsCategory();
        $data = Yii::$app->request->post();
        $where = ' id = '.$data['id'].' or parent_id = '.$data['id'];
        $ret = $model::deleteAll($where);
        if($ret > 0){
            //操作日志
            $this->saveLog($this->service,'删除商品分类','DEL',  '商品分类：ID = ' . $data['id']);
            $this->retJson('删除分类成功',200);
        }else{
            $this->retJson('删除分类失败',500);
        }
    }

    /**
     * 禁用商品分类
     */
    public function actionDisable(){
        $model = new GoodsCategory();
        $data = Yii::$app->request->post();

        $mod_data['use_flg'] = 0;
        $mod_data['editor'] = $model->getCreator();
        $mod_data['edit_time'] = date('Y-m-d H:i:s',time());
        $res = $model::updateAll($mod_data, "id=:id or parent_id=:id",array(':id'=>$data['id']));

        if($res > 0){
            //操作日志
            $this->saveLog($this->service,'禁用商品分类','USEFLG0','ID=' . $data['id'] . "\r\n" .  \yii\helpers\Json::encode($mod_data));
            $this->retJson('商品分类禁用成功',200);
        }else{
            $this->retJson('商品分类禁用失败',500);
        }
    }

    /**
     * 启用商品分类
     */
    public function actionEnable(){
        $model = new GoodsCategory();
        $data = Yii::$app->request->post();

        $mod_data['use_flg'] = 1;
        $mod_data['editor'] = $model->getCreator();
        $mod_data['edit_time'] = date('Y-m-d H:i:s',time());

        /*$model::updateAll(['use_flg' => 0], ['or','id'=> $data['id'],'parent_id'=>$data['id']]);*/
        $res = $model::updateAll($mod_data, "id=:id",array('id'=>$data['id']));

        if($res > 0){
            //操作日志
            $this->saveLog($this->service,'启用商品分类','USEFLG1','ID=' . $data['id'] . "\r\n" . \yii\helpers\Json::encode($mod_data));
            $this->retJson('商品分类启用成功',200);
        }else{
            $this->retJson('商品分类启用失败',500);
        }
    }
    
    /**
     * 禁用推荐分类
     */
    public function actionDisableRecommend(){
        $model = new CategoryRecommend();
        $data = Yii::$app->request->post();
        
        $mod_data['use_flg'] = 0;
        $mod_data['editor'] = $model->getCreator();
        $mod_data['edit_time'] = date('Y-m-d H:i:s',time());
        $res = $model::updateAll($mod_data, "id=:id",array(':id'=>$data['id']));
        
        if($res > 0){
            //操作日志
            $this->saveLog($this->service,'禁用推荐分类','USEFLG0','ID=' . $data['id'] . "\r\n" .  \yii\helpers\Json::encode($mod_data));
            $this->retJson('商品推荐分类禁用成功',200);
        }else{
            $this->retJson('商品推荐分类禁用失败',500);
        }
    }
    
    /**
     * 启用推荐分类
     */
    public function actionEnableRecommend(){
        $model = new CategoryRecommend();
        $data = Yii::$app->request->post();
        
        $mod_data['use_flg'] = 1;
        $mod_data['editor'] = $model->getCreator();
        $mod_data['edit_time'] = date('Y-m-d H:i:s',time());
        
        /*$model::updateAll(['use_flg' => 0], ['or','id'=> $data['id'],'parent_id'=>$data['id']]);*/
        $res = $model::updateAll($mod_data, "id=:id",array('id'=>$data['id']));
        
        if($res > 0){
            //操作日志
            $this->saveLog($this->service,'启用推荐分类','USEFLG1','ID=' . $data['id'] . "\r\n" . \yii\helpers\Json::encode($mod_data));
            $this->retJson('商品推荐分类启用成功',200);
        }else{
            $this->retJson('商品推荐分类启用失败',500);
        }
    }

    /**
     * 获取分类品类关系
     */
    public function actionGetCateRelation(){
        $data = Yii::$app->request->post();
        $where = "category_id=:category_id and use_flg=:use_flg";
        $where_param = array(':category_id'=>$data['id'],':use_flg'=>1);
        $list = GoodsCateRelation::find()->where($where,$where_param)->asArray()
            ->select('tag_id')->orderBy(array('id'=>SORT_ASC))->all();
        if(!empty($list)){
            $tag_list = implode(',',array_column($list,'tag_id'));
        }else{
            $tag_list = array();
        }
        return \yii\helpers\Json::encode($tag_list);
    }

    /**
     * 编辑分类品类关联
     */
    public function actionModCateRelation(){
        $model = new GoodsCateRelation();
        $data = Yii::$app->request->post();
        if(empty($data['old_tag_id'])){
            $data['old_tag_id'] = array();
        }else{
            $data['old_tag_id'] = explode(',',$data['old_tag_id']);
        }

        if(empty($data['tag_id'])){
            $data['tag_id'] = array();
        }else{
            $add_tag = $data['tag_id'];
        }

        //获取品类
        $tag = GoodsTag::find()->select('id,tag_group_name,tag_group_alias,tag_name,tag_alias,tag_group_id')->asArray()->all();
        $tag_list = array();
        foreach($tag as $value){
            $tag_list[$value['id']]['tag_name'] = $value['tag_name'];
            $tag_list[$value['id']]['tag_alias'] = $value['tag_alias'];
            $tag_list[$value['id']]['tag_group_name'] = $value['tag_group_name'];
            $tag_list[$value['id']]['tag_group_id'] = $value['tag_group_id'];
            $tag_list[$value['id']]['tag_group_alias'] = $value['tag_group_alias'];
        }

        $transaction = Yii::$app->db->beginTransaction();
        try{
            if(!empty($data['old_tag_id'])){
                //删除旧品类
                $where = ['category_id'=>$data['category_id']];
                $res = $model::deleteAll($where);
                if(!$res){
                    throw new \Exception('操作失败');
                }
            }

            if(!empty($add_tag)){
                //添加新的品类
                $list = array();
                foreach($add_tag as $key=>$value){
                    $list[] = [$value,$data['category_id'],1,$model->getCreator(),date('Y-m-d H:i:s',time()),$tag_list[$value]['tag_group_id'],
                        $tag_list[$value]['tag_group_name'],$tag_list[$value]['tag_group_alias'],$tag_list[$value]['tag_name'],
                        $tag_list[$value]['tag_alias']];
                }
                $field_name = ['tag_id','category_id','use_flg','creator','create_time','tag_group_id',
                    'tag_group_name','tag_group_alias','tag_name','tag_alias'];
                $ret = Yii::$app->db->createCommand()->batchInsert('j_goods_cate_relation', $field_name, $list)->execute();
                if(!$ret){
                    throw new \Exception('操作失败');
                }
            }

            $transaction->commit();
            //操作日志
            $this->saveLog($this->service,'品类关联','MOD',  '商品分类,ID = ' .  $data['category_id']);
            $this->retJson('编辑成功',200);
        }catch (\Exception $e){
            $transaction->rollBack();
            //add by allen.qiang 20180112 异常处理，日志优化 start
            error_log('error->' . __METHOD__ . ' error:' . $e->getMessage());
            //add by allen.qiang 20180112 异常处理，日志优化 end
            $this->retJson($e->getMessage(),500);
        }
    }

    /**
     * 导航相关修改时清空导航redis缓存
     * action 方法名
     */
    public function beforeAction($action){

        $currentaction = $action->id;

        $novalidactions = ['add-category','get-one-category','enable','disable','update-category','del-category',
            'mod-cate-relation','mod-brand-relation'];

        if(in_array($currentaction,$novalidactions)){

            \common\helps\tools::delWebNavRedis();

        }
        parent::beforeAction($action);

        return true;
    }

    /**
     * 获取分类品牌关系
     */
    public function actionGetBrandRelation(){
        $data = Yii::$app->request->post();
        $where = ['category_id'=>$data['id'],'use_flg'=>1];
        //mod by lizenan 20180118 【后台管理】商品分类中选择品牌逻辑调整     468  start
        //$list = GoodsCategoryBrRelation::find()->where($where)->asArray()->select('brand_id')->orderBy(array('id'=>SORT_ASC))->all();
        $list = GoodsCategoryBrRelation::find()->where($where)->asArray()->select('brand_id,group_id')->orderBy(array('id'=>SORT_ASC))->all();
        if(!empty($list)){
            //foreach循环 add  468
            foreach ($list as &$list_val){
                $list_val['brand_id'] = $list_val['brand_id'].'_'.$list_val['group_id'];
            }
            $tag_list = implode(',',array_column($list,'brand_id'));
        }else{
            $tag_list = array();
        }
        //mod by lizenan 20180118 【后台管理】商品分类中选择品牌逻辑调整     468  end
        return \yii\helpers\Json::encode($tag_list);
    }

    /**
     * 编辑分类品牌关系
     */
    public function actionModBrandRelation(){
        $model = new GoodsCategoryBrRelation();
        $data = Yii::$app->request->post();
        if(empty($data['old_brand_id'])){
            $data['old_brand_id'] = array();
        }else{
            $data['old_brand_id'] = explode(',',$data['old_brand_id']);
        }
        $category_list = array();
        $category_data = GoodsCategory::find()->select('id,category_name')->asArray()->all();
        foreach($category_data as $value){
            $category_list[$value['id']]['category_name'] = $value['category_name'];
        }

        //$list_value = '';

        if(!empty($data['brand_id'])){
            $list_value = $data['brand_id'];
            foreach($list_value as $value){
                $explode_value = explode('__',$value);
                $brand_id_list[] = $explode_value[0];
                $brand_name_list[] = $explode_value[1];
                $group_id_list[] = $explode_value[2];
                $group_name_list[] = $explode_value[3];
                $group_alias_list[] = $explode_value[4];
            }
        }

        $transaction = Yii::$app->db->beginTransaction();
        try{
            if(!empty($data['old_brand_id'])){
                //删除旧的分类品牌关系
                $where = ['category_id'=>$data['category_id']];
                $res = $model::deleteAll($where);
                if(!$res){
                    throw new \Exception('操作失败');
                }
            }

            if(!empty($list_value)){
                //添加新的分类品牌关系
                $list = array();
                foreach($brand_id_list as $key=>$value){
                    $list[] = [$value,$data['category_id'],$category_list[$data['category_id']]['category_name'],
                        $brand_name_list[$key],$group_id_list[$key],$group_name_list[$key],$group_alias_list[$key],1,$model->getCreator(),date('Y-m-d H:i:s',time())];
                }
                $field_name = ['brand_id','category_id','category_name','brand_name','group_id','group_name','group_alias','use_flg','creator','create_time'];
                $ret = Yii::$app->db->createCommand()->batchInsert('j_goods_category_br_relation', $field_name, $list)->execute();
                if(!$ret){
                    throw new \Exception('操作失败');
                }
            }

            $transaction->commit();
            //操作日志
            $this->saveLog($this->service,'品牌关联','MOD',  '商品分类,ID = ' .  $data['category_id']);
            $this->retJson('编辑成功',200);
        }catch (\Exception $e){
            $transaction->rollBack();
            //add by allen.qiang 20180112 异常处理，日志优化 start
            error_log('error->' . __METHOD__ . ' error:' . $e->getMessage());
            //add by allen.qiang 20180112 异常处理，日志优化 end
            $this->retJson($e->getMessage(),500);
        }
    }

    //获取分类推荐
    public function actionGetRecommend(){
        $data = Yii::$app->request->post();
        $count = 0;
        $list = array();
        if(!empty($data['table_category_id'])){

            if(!empty($data['recommend_name'])){
                $condition = "category_id = ".$data['table_category_id']." and recommend_name like '%".$data['recommend_name']."%'";
                $where = array();
            }else{
                $condition = "category_id=:category_id";
                $where = array(':category_id'=>$data['table_category_id']);
            }
            $query = CategoryRecommend::find()->where($condition,$where);
            $count = $query->count();
            //$pagination = new Pagination(['totalCount' => $count]);
            //$pagination->pageSizeLimit = [$data['start'] > 0 ? $data['start'] : 1 ,$data['length']];
            $sort_string = empty($data['columns'][$data['order'][0]['column']]['data']) ? 'id' : $data['columns'][$data['order'][0]['column']]['data'];
            $list = $query->offset($data['start'])->limit($data['length'])
                ->orderBy(array("$sort_string"=>$data['order'][0]['dir'] == 'asc' ? SORT_ASC : SORT_DESC))->all();
            if(empty($list)){
                $list = array();
            }
        }

        //相关参数   http://datatables.club/manual/server-side.html
        $result['draw'] = intval($data['draw']);
        $result['recordsTotal'] = intval($count);
        $result['recordsFiltered'] = intval($count);
        $result['data'] = $list;
        return \yii\helpers\Json::encode($result);
    }

    /**
     * 添加分类推荐及推荐商品
     */
    public function actionAddRecommend(){
        $model = new CategoryRecommend();
        $category_list = array();
        $category_data = GoodsCategory::find()->select('id,category_name')->asArray()->all();
        foreach($category_data as $value){
            $category_list[$value['id']]['category_name'] = $value['category_name'];
        }

        $data = Yii::$app->request->post();

        $data_now['recommend_name'] = trim($data['recommend_name']);
        $data_now['category_id'] = $data['category_id'];
        $data_now['category_name'] = $category_list[$data['category_id']]['category_name'];
        $data_now['create_time'] = date('Y-m-d H:i:s',time());
        $data_now['creator'] = $model->getCreator();
        $data_now['use_flg'] = $data['use_flg'];
        $data_now['sort'] = empty($data['sort']) ? 1 : $data['sort'];

        if(!empty($data['goods_id'])){
            $goods_id_list = $data['goods_id'];
            $goods_sort_list = $data['goods_sort'];

            //删除数组中空的元素
            foreach($goods_id_list as $value){
                if(empty($value)){
                    /*$num = array_search($value,$goods_id_list);
                    array_splice($goods_id_list,$num,1);
                    array_splice($goods_sort_list,$num,1);*/
                    $this->retJson('请删除空数据之后在提交',500);
                }
            }

            //去重
            $goods_id = array_unique($goods_id_list);

            // 查询商品物料号是否存在 并查找出 goods_id 和 main_goods_id
            $goods_sku_where = ['sku'=>$goods_id];
            $goods_sku = GoodsSaleEdit::find()->where($goods_sku_where)->select('sku,goods_id,main_goods_id')->asArray()->all();
            if(empty($goods_sku)){
                $this->retJson('物料号填写错误',500);
            }

            $goods_list = array();
            foreach($goods_sku as $value){
                $goods_list[$value['sku']] = $value;
            }

            foreach($goods_id as $value){
                if(empty($goods_list[$value])){
                    $this->retJson('不存在物料号:' . $value,500);
                }
            }
        }

        $transaction = Yii::$app->db->beginTransaction();
        try{

            $res = Yii::$app->db->createCommand()->insert('j_category_recommend',$data_now)->execute();
            $new_id = Yii::$app->db->getLastInsertID();
            if(!$res){
                throw new \Exception('操作失败');
            }

            if(!empty($goods_id) && !empty($goods_sort_list)){
                $list = array();
                foreach($goods_id as $key=>$value){
                    $list[] = [$new_id,$data_now['recommend_name'],$value,$goods_list[$value]['goods_id'],$goods_list[$value]['main_goods_id'],1,
                        $goods_sort_list[$key],$model->getCreator(),date('Y-m-d H:i:s',time())];
                }
                $field_name = ['category_recommend_id','category_recommend_name','sku','goods_id','main_goods_id','use_flg','sort','creator','create_time'];
                $ret = Yii::$app->db->createCommand()->batchInsert('j_category_recommend_goods', $field_name, $list)->execute();
                if(!$ret){
                    throw new \Exception('操作失败');
                }
            }

            $transaction->commit();
            //操作日志
            $this->saveLog($this->service,'添加分类推荐及推荐商品','MOD',  '商品分类：' .  $data_now['category_name']);
            $this->retJson('编辑成功',200);
        }catch (\Exception $e){
            $transaction->rollBack();
            //add by allen.qiang 20180112 异常处理，日志优化 start
            error_log('error->' . __METHOD__ . ' error:' . $e->getMessage());
            //add by allen.qiang 20180112 异常处理，日志优化 end
            $this->retJson('操作失败',500);
        }
    }

    /**
     * 获取单条分类推荐记录及相关商品
     */
    public function actionGetCategoryRecommend(){
        $model = new CategoryRecommend();
        $data = Yii::$app->request->post();

        $list = $model::find()->where("id=:id",array(':id'=>$data['id']))->asArray()->one();
        $recommend_list = CategoryRecommendGoods::find()->where("category_recommend_id=:id",array(':id'=>$data['id']))->asArray()->all();
        if(empty($recommend_list)){
            $recommend_list = array();
        }
        $list['recommend_list'] = $recommend_list;
        return \yii\helpers\Json::encode($list);
    }

    /**
     * 编辑分类推荐以及推荐商品
     */
    public function actionUpdateRecommend(){
        $model = new CategoryRecommend();
        $category_list = array();
        $category_data = GoodsCategory::find()->select('id,category_name')->asArray()->all();
        foreach($category_data as $value){
            $category_list[$value['id']]['category_name'] = $value['category_name'];
        }

        $data = Yii::$app->request->post();

        $data_now['recommend_name'] = trim($data['recommend_name']);
        $data_now['category_id'] = $data['category_id'];
        $data_now['category_name'] = $category_list[$data['category_id']]['category_name'];
        $data_now['edit_time'] = date('Y-m-d H:i:s',time());
        $data_now['editor'] = $model->getCreator();
        $data_now['use_flg'] = $data['use_flg'];
        $data_now['sort'] = empty($data['sort']) ? 1 : $data['sort'];

        if(!empty($data['goods_id'])){
            $goods_id_list = $data['goods_id'];
            $goods_sort_list = $data['goods_sort'];

            //删除数组中空的元素
            foreach($goods_id_list as $value){
                if(empty($value)){
                    /*$num = array_search($value,$goods_id_list);
                    array_splice($goods_id_list,$num,1);
                    array_splice($goods_sort_list,$num,1);*/
                    $this->retJson('请删除空数据之后在提交',500);
                }
            }

            //去重
            $goods_id = array_unique($goods_id_list);

            // 查询商品物料号是否存在 并查找出 goods_id 和 main_goods_id
            $goods_sku_where = ['sku'=>$goods_id];
            $goods_sku = GoodsSaleEdit::find()->where($goods_sku_where)->select('sku,goods_id,main_goods_id')->asArray()->all();
            if(empty($goods_sku)){
                $this->retJson('物料号填写错误',500);
            }

            $goods_list = array();
            foreach($goods_sku as $value){
                $goods_list[$value['sku']] = $value;
            }

            foreach($goods_id as $value){
                if(empty($goods_list[$value])){
                    $this->retJson('不存在物料号:' . $value,500);
                }
            }
        }
        $transaction = Yii::$app->db->beginTransaction();
        try{
            $res = $model::updateAll($data_now, "id=:id",array(':id'=>$data['recommend_id']));
            if(!$res){
                throw new \Exception('编辑失败');
            }

            //删除旧的关联商品
            $result = CategoryRecommendGoods::find()
                ->where("category_recommend_id=:category_recommend_id",array(':category_recommend_id'=>$data['recommend_id']))
                ->asArray()->select('id')->one();

            if(!empty($result)){
                $where = ['category_recommend_id'=>$data['recommend_id']];
                $ret = CategoryRecommendGoods::deleteAll($where);
                if(!$ret){
                    throw new \Exception('操作失败');
                }
            }

            if(!empty($goods_id) && !empty($goods_sort_list)){
                $list = array();
                foreach($goods_id as $key=>$value){
                    $list[] = [$data['recommend_id'],$data_now['recommend_name'],$value,$goods_list[$value]['goods_id'],$goods_list[$value]['main_goods_id'],
                        1,$goods_sort_list[$key],$model->getCreator(),date('Y-m-d H:i:s',time())];
                }
                $field_name = ['category_recommend_id','category_recommend_name','sku','goods_id','main_goods_id','use_flg','sort','creator','create_time'];
                $red = Yii::$app->db->createCommand()->batchInsert('j_category_recommend_goods', $field_name, $list)->execute();
                if(!$red){
                    throw new \Exception('操作失败');
                }
            }

            $transaction->commit();
            $this->retJson('编辑成功',200);
        }catch (\Exception $e){
            $transaction->rollBack();
            //add by allen.qiang 20180112 异常处理，日志优化 start
            error_log('error->' . __METHOD__ . ' error:' . $e->getMessage());
            //add by allen.qiang 20180112 异常处理，日志优化 end
            $this->retJson('操作失败',500);
        }
    }
    
    public function actionGetGoodsRelation(){
        $data = Yii::$app->request->post();
        $category_id = $data['id'];
        $where = ['relation_key'=>'category_'.$category_id];
        $result = GoodsRelation::find()->select('id,main_goods_id,sku')->where($where)->orderBy('sort asc')->asArray()->all();
        $this->retJson($result,200);
    }
    
    public function actionSaveGoodsRelation(){
        $data = Yii::$app->request->post();
        $transaction = Yii::$app->db->beginTransaction();
        try {
            $category_id = $data['category_id'];
            $sku = $data['sku'];
            $goods_relation_id = $data['goods_relation_id'];
            $operTime = date('Y-m-d H:i:s',time());
            $relation_key = 'category_'.$category_id;
            $goods_relation_s = GoodsRelation::find()->where('relation_key="'.$relation_key.'"')->asArray()->all();
            $old_relation_id = array_column($goods_relation_s, 'id');
            $sort = 1;
            if (is_array($goods_relation_id) && count($goods_relation_id) > 0)for ($i=0;$i<count($goods_relation_id);$i++){
                $goods_relation = new GoodsRelation();
                $oper = $goods_relation->getCreator();
                $where = array();
                if ($sku[$i] == '') continue;
                if ($goods_relation_id[$i]){
                    $goods_relation = GoodsRelation::findOne($goods_relation_id[$i]);
                    $goods_relation->editor = $oper;
                    $goods_relation->edit_time = $operTime;
                }else{
                    $goods_relation->creator = $oper;
                    $goods_relation->create_time = $operTime;
                    $goods_relation->use_flg = 1;
                }
                $where['sku'] = $sku[$i];
                $goods_sale = GoodsSaleEdit::find()->where($where)->asArray()->one();
                if (!count($goods_sale)) {
                    throw new \Exception('操作失败，商品不存在');
                }
                $list_id_where = ['goods_id'=>$goods_sale['goods_id']];
                $goods_list = GoodsListEdit::find()->where($list_id_where)->asArray()->one();
                if (!$goods_list) {
                    throw new \Exception('操作失败，物料号【'.$sku[$i].'】商品不是主商品');
                }
                $goods_relation->relation_key = $relation_key;
                $goods_relation->main_goods_id = $goods_sale['main_goods_id'];
                $goods_relation->goods_id = $goods_sale['goods_id'];
                $goods_relation->sku = $sku[$i];
                $goods_relation->goods_name_cn = $goods_sale['goods_name_cn'];
                $goods_relation->sort = $sort;
                $goods_relation->save();
                $save_relation_id = $goods_relation->attributes['id'];
                if (!$save_relation_id){
                    throw new \Exception('分类搭配商品添加失败');
                }
                $sort++;
            }
            if (is_array($old_relation_id) && count($old_relation_id))foreach ($old_relation_id as $relation_id){
                if (!in_array($relation_id,$goods_relation_id)){
                    $relationDel = GoodsRelation::deleteAll(['id'=>$relation_id]);
                    if(!$relationDel){
                        throw new \Exception('操作失败');
                    }
                }
            }
            $transaction->commit();
            $this->retJson('操作成功',200);
        }catch (\Exception $e){
            $transaction->rollBack();
            //add by allen.qiang 20180112 异常处理，日志优化 start
            error_log('error->' . __METHOD__ . ' error:' . $e->getMessage());
            //add by allen.qiang 20180112 异常处理，日志优化 end
            $this->retJson($e->getMessage(),500);
        }
    }
}